package lc.q51_100;

import lc.q101_150.ListNode;

import java.util.ArrayList;
import java.util.List;

public class Q92 {

    public ListNode reverseBetween(ListNode head, int left, int right) {
        List<ListNode> needRevertNodes = new ArrayList<>();
        ListNode prev = new ListNode();
        prev.next = head;
        ListNode cur = head;
        ListNode pv = prev;
        for (int i = 0; i < right && cur != null; i++) {
            if (i + 1 < left) {
                pv = pv.next;
            }
            if (i +1 >= left && i + 1 <= right) {
                needRevertNodes.add(cur);
            }
            cur = cur.next;
        }

        for (int i = 0; i < needRevertNodes.size(); i++) {
            ListNode listNode = needRevertNodes.get(i);
            listNode.next = cur;
            cur = listNode;
        }
        pv.next = cur;
        return prev.next;
    }

    public static void main(String[] args) {
        ListNode listNode = ListNode.buildByArr(new int[]{1, 4, 3, 2, 5});
        Q92 q92 = new Q92();
        ListNode listNode1 = q92.reverseBetween(listNode, 2, 4);
        System.out.println(listNode1);
        System.out.println(q92.reverseBetween(ListNode.buildByArr(new int[]{5}), 1, 1));
    }
}
